package com.wang.gallerybackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.gallerybackend.exception.BusinessException;
import com.wang.gallerybackend.exception.ErrorCode;
import com.wang.gallerybackend.exception.ThrowUtils;
import com.wang.gallerybackend.manager.sharding.DynamicShardingManager;
import com.wang.gallerybackend.model.dto.space.SpaceAddRequest;
import com.wang.gallerybackend.model.dto.space.SpaceQueryRequest;
import com.wang.gallerybackend.model.entity.Space;
import com.wang.gallerybackend.model.entity.SpaceUser;
import com.wang.gallerybackend.model.entity.User;
import com.wang.gallerybackend.model.enums.SpaceLevelEnum;
import com.wang.gallerybackend.model.enums.SpaceRoleEnum;
import com.wang.gallerybackend.model.enums.SpaceTypeEnum;
import com.wang.gallerybackend.model.vo.SpaceVO;
import com.wang.gallerybackend.model.vo.UserVO;
import com.wang.gallerybackend.service.SpaceUserService;
import com.wang.gallerybackend.service.UserService;
import com.wang.gallerybackend.service.SpaceService;
import com.wang.gallerybackend.mapper.SpaceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author 汪
 * @description 针对表【user_space(用户空间表)】的数据库操作Service实现
 * @createDate 2025-08-13 10:38:17
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
		implements SpaceService {
	@Resource
	private UserService userService;
	@Resource
	private TransactionTemplate transactionTemplate;
	@Resource
	private SpaceUserService spaceUserService;
	Map<Long, Object> lockMap = new ConcurrentHashMap<>();
/*	@Autowired
	@Lazy
	private DynamicShardingManager dynamicShardingManager;*/


	@Override
	public void validSpace(Space space, boolean add) {
		ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
		// 从对象中取值
		String spaceName = space.getSpaceName();
		Integer spaceLevel = space.getSpaceLevel();
		SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
		Integer spaceType = space.getSpaceType();
		SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
		ThrowUtils.throwIf(spaceLevelEnum == null, ErrorCode.PARAMS_ERROR, "空间级别不存在");
		// 如果传递了 url，才校验
		if (add) {
			ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ErrorCode.PARAMS_ERROR, "空间名称不能为空");
			ThrowUtils.throwIf(spaceLevel == null, ErrorCode.PARAMS_ERROR, "空间级别不能为空");
			ThrowUtils.throwIf(spaceType == null, ErrorCode.PARAMS_ERROR, "空间类型不能为空");
		}
		//修改数据时，id 不能为空，有参数则校验
		ThrowUtils.throwIf(StrUtil.isBlank(spaceName) && spaceName.length() > 30, ErrorCode.PARAMS_ERROR, "空间名称过长");
		ThrowUtils.throwIf(spaceLevel == null, ErrorCode.PARAMS_ERROR, "空间级别不能为空");
		//修改数据时，空间级别校验
		ThrowUtils.throwIf(spaceType != null && spaceTypeEnum == null, ErrorCode.PARAMS_ERROR, "空间类别不存在");
	}

	@Override
	public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
		QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
		if (spaceQueryRequest == null) {
			return queryWrapper;
		}
		// 从对象中取值
		Long id = spaceQueryRequest.getId();
		Long userId = spaceQueryRequest.getUserId();
		String spaceName = spaceQueryRequest.getSpaceName();
		Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
		Integer spaceType = spaceQueryRequest.getSpaceType();
		String sortField = spaceQueryRequest.getSortField();
		String sortOrder = spaceQueryRequest.getSortOrder();
		// 拼接查询条件
		queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
		queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
		queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
		queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
		queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
		// 排序
		queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
		return queryWrapper;
	}

	@Override
	public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
		List<Space> spaceList = spacePage.getRecords();
		Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
		if (CollUtil.isEmpty(spaceList)) {
			return spaceVOPage;
		}
		// 对象列表 => 封装对象列表
		List<SpaceVO> spaceVOList = spaceList.stream()
				.map(SpaceVO::objToVo)
				.collect(Collectors.toList());
		// 1. 关联查询用户信息
		// 1,2,3,4
		Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
		// 1 => user1, 2 => user2
		Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
				.collect(Collectors.groupingBy(User::getId));
		// 2. 填充信息
		spaceVOList.forEach(spaceVO -> {
			Long userId = spaceVO.getUserId();
			User user = null;
			if (userIdUserListMap.containsKey(userId)) {
				user = userIdUserListMap.get(userId).get(0);
			}
			spaceVO.setUser(userService.getUserVO(user));
		});
		spaceVOPage.setRecords(spaceVOList);
		return spaceVOPage;
	}

	@Override
	public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
		// 对象转封装类
		SpaceVO spaceVO = SpaceVO.objToVo(space);
		// 关联查询用户信息
		Long userId = space.getUserId();
		if (userId != null && userId > 0) {
			User user = userService.getById(userId);
			UserVO userVO = userService.getUserVO(user);
			spaceVO.setUser(userVO);
		}
		return spaceVO;
	}

	/**
	 * 根据空间级别填充空间信息
	 * @param space
	 */
	@Override
	public void fillSpaceBySpaceLevel(Space space) {
		Integer spaceLevel = space.getSpaceLevel();
		SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
		if (spaceLevelEnum != null) {
			long maxSize = spaceLevelEnum.getMaxSize();
			if (space.getMaxSize() == null) {
				space.setMaxSize(maxSize);
			}
			long maxCount = spaceLevelEnum.getMaxCount();
			if (space.getMaxCount() == null) {
				space.setMaxCount(maxCount);
			}
		}
	}

	@Override
	public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
		//1.填充参数默认值
		Space space = new Space();
		//复制属性
		BeanUtil.copyProperties(spaceAddRequest, space);
		if (StrUtil.isBlank(space.getSpaceName())) {
			space.setSpaceName("默认空间");
		}
		if (space.getSpaceLevel() == null) {
			space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
		}
		if (spaceAddRequest.getSpaceType() == null) {
			space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
		}
		this.fillSpaceBySpaceLevel(space);
		//2.校验参数
		validSpace(space, true);
		//3.校验权限
		Long userId = loginUser.getId();
		space.setUserId(userId);
		if (SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && !userService.isAdmin(loginUser)) {
			throw new BusinessException(ErrorCode.NOT_AUTH_ERROR, "无权限创建指定级别的空间");
		}
		//4，控制同一个用户创建一个私有空间以及一个团队空间
		Object lock = lockMap.computeIfAbsent(userId, k -> new Object());
		synchronized (lock) {
			try {
				Long newSpaceId = transactionTemplate.execute(status -> {
					//判断是否已有空间
					boolean exists = this.lambdaQuery()
							.eq(Space::getUserId, userId)
							.eq(Space::getSpaceType, space.getSpaceType())
							.exists();
					if (exists) {
						throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已创建过空间,用户每类空间只能创建一个!!!");
					}
					//创建
					boolean save = this.save(space);
					if (!save) {
						throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建空间失败");
					}
					//如果是团队空间，关联新增团队的成员记录，把创建的人加入空间
					if (SpaceTypeEnum.TEAM.getValue() == (space.getSpaceType())) {
						SpaceUser spaceUser = new SpaceUser();
						spaceUser.setSpaceId(space.getId());
						spaceUser.setUserId(userId);
						spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
						boolean result = spaceUserService.save(spaceUser);
						if (!result) {
							throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建团队空间失败");
						}
					}
					/*//为旗舰版创建一个新表
					dynamicShardingManager.createSpacePictureTable(space);*/
					return space.getId();
				});
				return Optional.ofNullable(newSpaceId).orElse(-1L);
			} finally {
				lockMap.remove(userId);
			}
		}
	}

	@Override
	public void checkSpaceAuth(User loginUser, Space space) {
		//仅本人或管理员可编辑
		if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
			throw new BusinessException(ErrorCode.NOT_AUTH_ERROR);
		}
	}
}
